package com.gientech.springexercise.controller.redis02;

import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName User01Controller
 * @Description TODO
 * @Author zhangfantong
 * @Date 2023/2/16 20:26
 * @Version 1.0
 */
@RestController
@RequestMapping("/user01")
public class User01Controller {
    @Resource
    RedisTemplate redisTemplate;
    final String LOCK_KEY01= "mylock01";
    final String LOCK_KEY02= "mylock02";

    @GetMapping("/have")
    public String haveLock(){
        boolean flag = redisTemplate.opsForValue().setIfAbsent(LOCK_KEY01, "user01");
        if (flag){
            return "竞争成功";
        }
        return "竞争失败";
    }

    @GetMapping("/time")
    public String timeLock(){
        redisTemplate.opsForValue().setIfAbsent(LOCK_KEY02, "user01", 5, TimeUnit.SECONDS);
        if (redisTemplate.opsForValue().get(LOCK_KEY02).equals("user01")){
            return "正在占用";
        }
        return "等待锁";
    }
}
